package com.chenhb.watermarkutils;

import com.chenhb.watermarkutils.bo.WatermarkBo;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 图片添加文字水印工具
 *
 * @author 陈海波
 * @date 2021-04-21
 */
public class ImageTextWatermarkUtil {
    /**
     * 图片添加文字水印
     *
     * @param watermarkBo
     */
    public static ByteArrayOutputStream mark(WatermarkBo watermarkBo) throws IOException {
        ByteArrayOutputStream os = null;
        try {
            // 读取原图片信息
            File srcImgFile = watermarkBo.getResourceFile();
            Image srcImg = ImageIO.read(srcImgFile);
            int srcImgWidth = srcImg.getWidth(null);
            int srcImgHeight = srcImg.getHeight(null);
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            Font font = new Font("宋体", Font.PLAIN, watermarkBo.getFontSize());
            // 根据图片的背景设置水印颜色
            g.setColor(watermarkBo.getColor());
            g.setFont(font);
            g.rotate(watermarkBo.getDegree());
            // 设置水印位置
            g.drawString(watermarkBo.getWatermarkContent(), watermarkBo.getOffsetX(), watermarkBo.getOffsetY());
            g.dispose();
            // 输出图片
            os = new ByteArrayOutputStream();
            // 获取文件后缀
            String fileName = watermarkBo.getResourceFile().getName();
            String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
            ImageIO.write(bufImg, prefix, os);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return os;
    }

    /**
     * 获取水印文字总长度
     *
     * @param waterMarkContent 水印的文字
     * @param g
     * @return 水印文字总长度
     */
    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }
}
